﻿'use strict';

/* Services */

angular.module('ishaCrmApp.services', [])

    .value('version', '0.1')

    .service('googleAuthService', ['$http', '$rootScope', '$q', '$cookieStore', function ($http, $rootScope, $q, $cookieStore) {

        var deferred = $q.defer();

        this.checkLogin = function () {

            var cookieValue = $cookieStore.get(app.CLIENT_ID);

            if (cookieValue && cookieValue == app.CookieValue) {
                gapi.auth.authorize({
                    client_id: app.CLIENT_ID,
                    scope: app.SCOPES,
                    immediate: true
                }, this.handleAuthResult);
            }
            
            return deferred.promise;
        }

        this.login = function () {
            gapi.auth.authorize({
                client_id: app.CLIENT_ID,
                scope: app.SCOPES,
                response_type: app.RESPONSE_TYPE,
                immediate: false,
                authuser: '' //For Multiple logins, if you set authuser to empty then it will prompt with list of logins to select. But, user has to select the right Google Account twice
            }, this.handleAuthResult);

            return deferred.promise;
        }

        this.handleAuthResult = function (authResult) {

            if (authResult && !authResult.error) {
                gapi.client.oauth2.userinfo.get().execute(function (resp) {
                    deferred.resolve(resp);
                });
            } else {
                deferred.reject((authResult && authResult.error ? authResult.error : 'Error'));
            }

        }
    }]);


